package com.competitions.videoedithelper.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

public class TokenUtil {

    /****
     * 默认为10天的token
     * @param uid 用户id
     * @param userName 用户名
     * @return 返回token
     */
    public static String createToken(String uid,String userName){
        String token;
        token= JWT.create().withClaim("uid",uid)
                .withClaim("generatetime",System.currentTimeMillis())
                //设置token过期时间为10天
                .withClaim("exptime", 1000 * 60 * 60 * 24 * 10)
                .sign(Algorithm.HMAC256(userName));
        return token;
    }
    /****
     * 返回参数
     * @param token token
     * @return
     * true：toke有效
     * false：token无效
     */
    public static boolean decodeToken(String token){
        Long currentTime = System.currentTimeMillis();
        try {
            Long generateTime = JWT.decode(token).getClaim("generatetime").asLong();
            Long expTime = JWT.decode(token).getClaim("exptime").asLong();
            return currentTime - generateTime <= expTime;
        }catch (Exception e){
            return false;
        }
    }
}
